<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\admin\model\Trade as tradeModel;
use app\admin\service\TradeService;
use think\facade\View;

class Trade extends Diluma
{

    /**
     * 首页
     * @return string
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 列表数据
     * @return \think\response\Json
     */
    public function getTradeList(){
        $service = new TradeService();
        $items = $service->getTradeList();
        return json(['code'=>0, 'count'=>$items->total(), 'data'=>$items->items()]);
    }

    /**
     * 新增行业分类
     * @return mixed
     */
    public function insert(){
        $service = new TradeService();
        $categoryItems = $service->getTrades();
        if($this->request->isPost()) {
            $post = $this->request->post();
            return $service->updateOrInsert($post['field']);
        } else {
            $data['category_list'] = $categoryItems;
            $data['status'] = 0;
            View::assign('data', $data);
            return View::fetch();
        }
    }

    /**
     * 编辑行业分类
     * @return mixed
     */
    public function edit(){
        $service = new TradeService();
        $categoryItems = $service->getTrades();
        if($this->request->isPost()) {
            $id = $this->request->post('field.id');
            if($id <= 0){
                return $this->error('id不正确');
            }
            $post = $this->request->post();

            return $service->updateOrInsert($post['field']);
        } else {
            $id = $this->request->get('id');
            if($id <= 0){
                return $this->error('id不正确');
            }
            $data = $service->getOne((int)$id);
            $data['category_list'] = $categoryItems;
            View::assign('data', $data);
            return View::fetch();
        }
    }

    /**
     * 删除（单个/多个）
     * @describe 删除分类必须清空该分类下所有的子分类及职位
     * @return \think\response\Json
     */
    public function delete(){
        $post = $this->request->post();
        if(empty($post['id'])){
            return json(['code'=>1, 'msg'=>'参数异常']);
        }
        $id = $post['id'];
        if(is_array($id)){
            return json(['code'=>1, 'msg'=>'请单个删除记录']);
        } else{
            $service = new TradeService();
            return $service->delete($id);
        }
    }
}
